package com.wuad.platformwuad.module.study.http;


import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * 涉及调用外部HTTP请求相关
 *
 * @author wuaodi
 */
@RestController
@RequestMapping(value = "/platform")
@Slf4j
public class RequestHttp {

    /**
     * 模拟被调用的外部接口
     *
     * @param msg
     */
    @PostMapping("/submitAfsResult11")
    public void submitAfsResult11 (String msg) {
        log.info("111111111111:{}",msg);
    }


    /**
     * 调用外部接口
     *
     * @param map
     */
    @PostMapping("/submitAfsResult22")
    public void submitAfsResult22 (@RequestBody Map<String, Object> map) {
        try{
            log.info("传入值：{}", map);
            JSONObject jsonObject = new JSONObject(map);
//            JSONObject jsonObjectMsg = new JSONObject();
            Map<String, String> map1 = new HashMap<>();
            map1.put("msg", jsonObject.toJSONString());
            log.info("转map1后：{}", map1);
            doPost("http://localhost:9999/platform/submitAfsResult11", map1);
        }catch (Exception e) {
            log.info("地址调用异常：{}", e);
        }
    }


    /**
     * Java实现Postman中以form-data参数发送post请求
     *
     * @param url
     * @param paramMap
     * @return
     */
    public static String doPost(String url, Map<String, String> paramMap) {
// 创建Http实例
        CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建HttpPost实例
        HttpPost httpPost = new HttpPost(url);
        try {
            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
            builder.setCharset(java.nio.charset.Charset.forName("UTF-8"));
            builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
            //表单中参数
            for(Map.Entry<String, String> entry: paramMap.entrySet()) {
                builder.addPart(entry.getKey(),new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
            }

            HttpEntity entity = builder.build();
            httpPost.setEntity(entity);
            HttpResponse response = httpClient.execute(httpPost);// 执行提交

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 返回
                String res = EntityUtils.toString(response.getEntity(), java.nio.charset.Charset.forName("UTF-8"));
                return res;
            }

        } catch (Exception e) {
            e.printStackTrace();
            log.info("调用HttpPost失败！" + e.toString());
        } finally {
            if (httpClient != null) {
                try {
                    httpClient.close();
                } catch (IOException e) {
                    log.info("关闭HttpPost连接失败！");
                }
            }
        }
        return null;
    }

    /**
     * 调用外部接口，传json格式
     *
     * @param map
     */
    @PostMapping("/submitAfsResult")
    public void submitAfsResult (@RequestBody Map<String, Object> map) {
        // TODO: 2023/3/10 添加接口调用异常处理机制：接口调用是否成功，接口调用成功后对方系统是否修改成功。
        try{
            log.info("传入值：{}", map);
            JSONObject jsonObject = new JSONObject(map);
            JSONObject jsonObjectMsg = new JSONObject();
            Map<String, String> map1 = new HashMap<>();
            map1.put("msg", jsonObject.toJSONString());
            log.info("转map1后：{}", map1);
            jsonObjectMsg.put("msg", jsonObject);
            log.info("转json后：{}", jsonObjectMsg);
            CloseableHttpClient httpClient = HttpClients.createDefault();
            log.info("访问地址：{}");
            HttpPost httpPost = new HttpPost("http://localhost:9999/platform/submitAfsResult11");
            httpPost.setEntity(new StringEntity(map1.toString(),
                    ContentType.create("application/json", "UTF-8")));
            CloseableHttpResponse execute = httpClient.execute(httpPost);
            HttpEntity entity = execute.getEntity();
            log.info("返回数据实体：{}",entity);
            String str = EntityUtils.toString(entity);
            log.info("解析后的返回数据：{}",str);
            httpClient.close();
        }catch (Exception e) {
            log.info("地址调用异常：{}", e);
        }
    }

}
